package com.tim.app.ui.fragment.selceted;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.entry.SelectInfo;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.TopicProblemListResult;
import com.tim.app.ui.adapter.selceted.TopicDetailInfoItemAdapter;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;


/**
 * 问题列表
 */
public class ProblemListFragment extends BaseFragment implements View.OnClickListener, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    private static final String TAG = "ProblemListFragment";
    private View rootView;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvProblem;
    private EmptyLayout emptyLayout;
    private TopicDetailInfoItemAdapter adapter;
    private List<SelectInfo> dataList;
    private int pageNumber = 1;

    int type;
    private String topicId;
    private boolean isTopic;

    public static ProblemListFragment newInstance(int type, String topicId, boolean isTopic) {
        ProblemListFragment newFragment = new ProblemListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("type", type);
        bundle.putString("topicId", topicId);
        bundle.putBoolean("isTopic", isTopic);
        newFragment.setArguments(bundle);
        return newFragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_problem, container, false);

            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrvProblem = (WrapRecyclerView) rootView.findViewById(R.id.wrvProblem);

            wrvProblem.setOverScrollMode(View.OVER_SCROLL_NEVER);

            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            emptyLayout = new EmptyLayout(getActivity(), load_more);
            emptyLayout.showLoading();
            emptyLayout.setEmptyButtonClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    emptyLayout.showLoading();
                    initData(topicId, type);
                }
            });

            if (dataList == null) {
                dataList = new ArrayList<>();
            }
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrvProblem.setLayoutManager(layoutManager);
            wrvProblem.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.view_background_color)).size((int) getResources().getDimension(R.dimen.dimen_5)).build());
            Bundle args = getArguments();
            if (args != null) {
                type = args.getInt("type");
                if (args.containsKey("topicId")) {
                    topicId = args.getString("topicId");
                }
                isTopic = args.getBoolean("isTopic");
            }
            adapter = new TopicDetailInfoItemAdapter(getActivity(), dataList);
            adapter.setOnItemClickListener(this);
            wrvProblem.setAdapter(adapter);
        }

        initData(topicId, type);
        return rootView;
    }

    /**
     * 初始化数据
     *
     * @param topicId
     * @param type
     */
    private void initData(String topicId, int type) {
        if (AppKey.PROBLEM_TYPE_NEWEST == type) {
            API_Found.ins().getTopicLastProblemList(TAG, topicId, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
        } else if (AppKey.PROBLEM_TYPE_HOT == type) {
            API_Found.ins().getTopicHotProblemList(TAG, topicId, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvAddSubject:
                break;
        }
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        if (null != dataList && dataList.size() > position + 1) {
            ViewGT.gotoDetailActivity(getActivity(), dataList.get(position));
        }
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        if (AppKey.PROBLEM_TYPE_NEWEST == type) {
            API_Found.ins().getTopicLastProblemList(TAG, topicId, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
        } else if (AppKey.PROBLEM_TYPE_HOT == type) {
            API_Found.ins().getTopicHotProblemList(TAG, topicId, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errmsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                if (dataList != null) {
                    dataList.clear();
                }
                TopicProblemListResult result = new Gson().fromJson(resultValue, TopicProblemListResult.class);
                if (null != result.getRes() && result.getRes().getArraylist() != null) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    }
                } else {
                    load_more.loadMoreFinish(false, false);
                }
                if (dataList.size() == 0) {
                    emptyLayout.showEmpty();
                } else {
                    emptyLayout.showContent();
                }
            } else {
                load_more.loadMoreFinish(false, false);
                ToastUtil.showToast(errmsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errcode, String errmsg, int id, boolean fromcache) {
            if (errcode == ResponseResult.ResultStatus.OK && resultValue != null) {
                TopicProblemListResult result = new Gson().fromJson(resultValue, TopicProblemListResult.class);
                if (null != result.getRes() && result.getRes().getArraylist() != null) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, true);
                        } else {
                            load_more.loadMoreFinish(false, false);
                        }
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                } else {
                    load_more.loadMoreFinish(false, false);
                }
            } else {
                load_more.loadMoreFinish(false, false);
                ToastUtil.showToast(errmsg);
            }
            return false;
        }
    };

}
